"""cfg file patcher"""

import os
import re
import s3dutl

s3dcfg_p1 = re.compile(r'^.*=\s*"[^"]*".*$')

class s3dCfg:
   def __init__ (self, fileName):
      self.fileName = fileName
      self.fileLines = None
      self.lastMsg = ""
      self.Load()
   
   def GetLastMsg(self):
      return self.lastMsg
   
   def Load(self):
      f1 = open(self.fileName)
      self.fileLines = f1.readlines()
      f1.close()

   def Save(self):
      s3dutl.ClearReadOnly(self.fileName, False)
      f1 = open(self.fileName, 'w')
      f1.writelines(self.fileLines)
      f1.close()
   
   def PatchKey(self, key, value, log = False):
      for idx in range(len(self.fileLines)):
         add_str = ""
         if s3dcfg_p1.match(self.fileLines[idx]): add_str = '\"'
         new_line = re.sub(r"(\s*" + key + r"\s*)=([^{]*)$", 
                           r'\1= ' + add_str + value + add_str + '\n', 
                           self.fileLines[idx])      
         if new_line != self.fileLines[idx]:
            self.lastMsg = "patch cfg("+key+","+value+") old val: ("+self.fileLines[idx].strip(" \n")+")"
            if log:
               print self.lastMsg
            self.fileLines[idx] = new_line

   def GetKey(self, key, log = False):
      for idx in range(len(self.fileLines)):
         add_str = ""
         if s3dcfg_p1.match(self.fileLines[idx]): add_str = '\"'
         
         pattern2 = re.compile(r"(\s*" + key + r"\s*)=([^{]*)$")
         res = pattern2.match(self.fileLines[idx])
         if res:
            res_str = res.groups()[1].strip("\r\n "+add_str)
            self.lastMsg = "found key: " + key + " = " + res_str
            if log:
               print self.lastMsg
            return res_str
      self.lastMsg = "can't find key: " + key
      if log:
         print self.lastMsg
      return ""

def GetKeyGameCfg(key, defVal):
   keyValue = ""
   baseFile = ""
   
   if os.access("game_local.cfg", os.F_OK):
      cfg_local = s3dCfg("game_local.cfg")
      keyValue = cfg_local.GetKey(key)
      if keyValue == "":
         baseFile = cfg_local.GetKey("base")
   else:
      baseFile = "game.cfg"

   if baseFile != "":
      if os.access(baseFile, os.F_OK):
         cfg_base = s3dCfg(baseFile)
         keyValue = cfg_base.GetKey(key)
   
   if keyValue != "":
      return keyValue
   return defVal

def PatchKeyGameCfg(key, val, nochk = False):
   baseFile = ""
   
   if os.access("game_local.cfg", os.F_OK):
      cfg_local = s3dCfg("game_local.cfg")
      if nochk or cfg_local.GetKey(key) != "":
         cfg_local.PatchKey(key, val, True)
         cfg_local.Save()
      else:
         baseFile = cfg_local.GetKey("base")
   else:
      baseFile = "game.cfg"

   if baseFile != "":
      if os.access(baseFile, os.F_OK):
         cfg_base = s3dCfg(baseFile)
         cfg_base.PatchKey(key, val, True)
         cfg_base.Save()
         return

def PatchKeyUserCfg(key, val, nochk = False):
   if os.access("user.cfg", os.F_OK):
      cfg_local = s3dCfg("user.cfg")
      if nochk or cfg_local.GetKey(key) != "":
         cfg_local.PatchKey(key, val, True)
         cfg_local.Save()

